package com.ujoku.controller.admin.oa;

import com.easemob.server.httpclient.service.EasemobIMUsersService;
import com.labillusion.core.platform.crypto.MD5;
import com.labillusion.core.platform.exception.ResourceNotFoundException;
import com.labillusion.core.platform.web.pagination.PaginationView;
import com.labillusion.core.platform.web.rest.RESTController;
import com.labillusion.core.platform.web.rest.exception.InvalidRequestException;
import com.labillusion.core.util.StringUtils;
import com.ujoku.context.constants.ContextConstants;
import com.ujoku.context.constants.oa.MemberConstants;
import com.ujoku.domain.Member;
import com.ujoku.domain.admin.Parameter;
import com.ujoku.domain.admin.User;
import com.ujoku.request.admin.MemberListForm;
import com.ujoku.request.admin.oa.MemberCreateForm;
import com.ujoku.service.MemberService;
import com.ujoku.service.admin.ParametersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by suggestion on 2015/2/1.
 */
@RestController
public class OAMemberMngController extends RESTController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private ParametersService parametersService;

    @Autowired
    private EasemobIMUsersService easemobIMUsersService;

    @RequestMapping(value = "/uj-oa/member/list", method = RequestMethod.POST)
    @ResponseBody
    public PaginationView list(@RequestBody @Valid MemberListForm form,HttpServletRequest request) {
        checkAscription(form.getAscription(), request);

        Map<String, Object> query = new HashMap<>();
        int startIndex = form.getPageIndex() == 0 ? 0 : form.getPageIndex() * form.getPageSize();
        int pageSize = form.getPageSize();

        query.put("startIndex", startIndex);
        query.put("pageSize",pageSize);

        if (StringUtils.hasText(form.getReal_name()))
            query.put("real_name", form.getReal_name());
        if (StringUtils.hasText(form.getPhone_mob()))
            query.put("phone_mob", form.getPhone_mob());
        if (StringUtils.hasText(form.getAscription()))
            query.put("ascription", form.getAscription());

        PaginationView<Member> view = new PaginationView<>();
        List<Member> list = memberService.selectList(query);

        for(Member m : list){
            setLevelName(m);
        }

        view.setList(list);
        int count = memberService.selectCount(query);
        view.setCount(count);

        return view;

    }

    private void checkAscription(String ascrip, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        String ascription = (String) request.getSession().getAttribute("ascription");
        if(!user.getName().equals("oaAdmin") && !ascription.equals(ascrip)){
            throw new InvalidRequestException("归属地错误");
        }
    }

    private void setLevelName(Member member) {
        Parameter p = parametersService.getParameterByKey(ContextConstants.MEMBER_LEVEL + member.getLevel());
        if (p != null) {
            member.setLevelName(p.getMark());
            member.setDiscount(Double.parseDouble(p.getValue()));
        }
    }

    @RequestMapping(value = "/uj-oa/member/{id}", method = RequestMethod.GET)
    public Member getById(@PathVariable String id,HttpServletRequest request) {

        Member member = (Member)memberService.selectById(id);

        checkAscription(member.getAscription(),request);
        setLevelName(member);

        return member;
    }

    @RequestMapping(value = "/uj-oa/member", method = RequestMethod.POST)
    @ResponseBody
    public Member create(@RequestBody @Valid MemberCreateForm form,HttpServletRequest request){

        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            throw new ResourceNotFoundException("no user");
        }

        Member member = (Member) memberService.selectByUserName(form.getUser_name());
        if(member != null){
            throw new InvalidRequestException("member exists");
        }

        checkAscription(form.getAscription(),request);
        member = new Member();

        member.setUser_name(form.getUser_name());
        member.setPhone_mob(form.getPhone_mob());
        member.setReal_name(form.getReal_name());
        member.setPassword(MD5.encrypt(MemberConstants.PASSWORD));
        member.setPortrait(false);
        member.setScores(form.getScores());

        member.setCreateBy(user.getName());
        member.setUpdateBy(user.getName());

        member.setAscription(form.getAscription());

        memberService.insert(member);

        easemobIMUsersService.IMUserAsyncCreate(form.getUser_name());

        return member;
    }

    @RequestMapping(value = "/uj-oa/member", method = RequestMethod.PUT)
    @ResponseBody
    public Member update(@RequestBody @Valid Member member,HttpServletRequest request){

        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            throw new ResourceNotFoundException("no user");
        }

        Member mem = (Member) memberService.selectByUserName(member.getUser_name());
        if(mem != null && member.getUser_id() != mem.getUser_id()){
            throw new InvalidRequestException("Duplicate phone");
        }

        if(!StringUtils.hasText(member.getUser_name()))
            throw new InvalidRequestException("用户名不能为空");
        if(!StringUtils.hasText(member.getReal_name()))
            throw new InvalidRequestException("姓名不能为空");
        if(!StringUtils.hasText(member.getPhone_mob()))
            throw new InvalidRequestException("电话号码不能为空");
        if((Integer)member.getScores() == null)
            throw new InvalidRequestException("积分不能为空");
        if(!StringUtils.hasText(member.getAscription()))
            throw new InvalidRequestException("归属地不能为空");

        checkAscription(member.getAscription(),request);
        updateMember(member, user);

        return member;
    }

    private void updateMember(Member member, User user) {
        Member mem = (Member) memberService.selectById(member.getUser_id());

        member.setPassword(mem.getPassword());
        member.setPay_password(mem.getPay_password());
        member.setSecurity_code(mem.getSecurity_code());

        member.setUpdateBy(user.getName());

        memberService.update(member);
    }

    @RequestMapping(value = "/uj-oa/member/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public String updateStatus(@PathVariable String id,HttpServletRequest request){
        Member member = (Member) memberService.selectById(id);
        if(member == null)
            throw new ResourceNotFoundException("no menber");

        checkAscription(member.getAscription(),request);

        member.setStatus(!member.getStatus());

        memberService.updateStatus(member);

        return "successfully";
    }
}
